package com.example.dqnm.Interceptor;

import com.example.dqnm.utils.TokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    //重写preHandle方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //false:阻止；true:放行。
        String token = request.getHeader("token");
        // 如果没有携带token
        if (token == null) {
            throw new RuntimeException("please take token");
        }else if (!TokenUtils.verify(token)) {
            throw new RuntimeException("token error");
        }else {
//            String requestURI = request.getRequestURI();
//            if ("/user/userInfo".equals(requestURI)) {
                // 获取当前用户的openid
                String openid = TokenUtils.getOpenId(token);
                // 将openid设置到 /user/userInfo 对应的函数参数内
                request.getServletContext().setAttribute("openid", openid);
//            }
            return true;
        }
    }
}
